<?php

namespace App\ServicesNew\Impl;

use App\Entities\ProductEntity;
use App\Entities\ProductSkuEntity;
use App\Entities\ProductSkuModel;
use App\ServicesNew\ProductSkuService;
use Carbon\Carbon;

class ProductSkuServiceImpl implements ProductSkuService
{
    /**
     * @inheritDoc
     */
    public function getProductSkuEntityById(int $productSkuId)
    {
        return ProductSkuEntity::find($productSkuId);
    }

    /**
     * @inheritDoc
     */
    public function getUseAbleProductSkuEntitiesByProductEntity(ProductEntity $productEntity)
    {
        $productPid = $productEntity->getProductPid();
        if (0 === $productPid) {
            $productId = $productEntity->getId();
        } else {
            $productId = $productPid;
        }

        return $this->getUseAbleProductSkuEntities($productId, $productEntity->getProductCity(), $productEntity->getProductShowType());
    }

    /**
     * @inheritDoc
     */
    public function getUseAbleProductSkuEntities(int $productId, int $cityId, int $skuShowType)
    {
        $collection = ProductSkuModel::where('on_sale', ProductSkuModel::SKU_ON_SALE)
            ->where('purchase_product_id', 0)  // 不能为加购 sku
            ->where('product_id', $productId)
            ->where('city_id', $cityId)
            ->where(function ($query) {
                $query->where('begin_sale', '<=', Carbon::now())
                    ->orWhereNull('begin_sale');
            })
            ->where(function ($query) {
                $query->where('stop_sale', '>=', Carbon::now())
                    ->orWhereNull('stop_sale');
            })
            ->where('sku_show_type', $skuShowType)
            ->orderBy('order_by', 'asc')
            ->get();

        if ($collection->isEmpty()) {
            return [];
        }

        $ret = [];
        foreach ($collection as $model) {
            $ret[] = new ProductSkuEntity($model);
        }

        return $ret;
    }
}
